<?php

namespace app\common\service;

use app\common\model\Plugin;
use app\common\model\ThirdUser;
use app\common\model\Users;
use think\Collection;
use think\Request;

abstract class PlatformBaseService
{
    /**
     * @var mixed
     */
    protected $config;

    public function __construct()
    {
        $this->config = Plugin::where(['code' => $this->platform])->findOrFail()->getAttr('config_value');
    }

    /**
     * @param \app\common\model\Users $users
     * @param string $type
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function relationThird(Users $users, string $type = 'register')
    {
        $mpCode = \request()->param('mp_code');

        if (!$mpCode) {
            //            abort(400, '缺少code参数');
            return;
        }

        $result = $this->parseCode($mpCode);

        $thirdUser = ThirdUser::where('openid', $result['openid'])->find();

        if ($thirdUser) {
            if ($type === 'register') {
                abort(400, '该用户已经注册过');
            } elseif ($type === 'login') {
                return;
            }
        }


        ThirdUser::create([
            'uid'      => $users->getKey(),
            'openid'   => $result['openid'],
            'unionid'  => $result['unionid'] ?? '',
            'platform' => request()->header('platform', request()->param('platform')),
        ]);
    }

    /**
     * @return array|\think\Model
     */
    public function loginByPhone()
    {
        $mpCode = \request()->param('mp_code');

        if (!$mpCode) {
            abort(400, '缺少code参数');
        }

        $result = $this->parseCode($mpCode);

        $thirdUser = ThirdUser::where('openid', $result['openid'])->findOrEmpty();
        $thirdUser->openid = $result['openid'];
        $thirdUser->unionid = $result['unionid'] ?? '';
        $thirdUser->platform = request()->header('platform', request()->param('platform'));


        if ($this instanceof WechatOfficialService) {
            $user = $thirdUser->user ?: new Users();
            $user->nickname = '牧场用户-' . mt_rand(1, 1000);
        } else {
            $phone = $this->getPhoneNumber();
            $user = Users::where('mobile', $phone)->findOrEmpty();

            if ($user->mobile && $user->mobile !== $phone) {
                abort(400, '该手机号已经被注册');
            }

            $user->mobile = $phone;
            $user->nickname = $phone;
        }

        if ($user->getKey() && $thirdUser->uid && $user->getKey() !== $thirdUser->uid) {
            abort(400, '该账号已经被注册');
        }

        if (!$user->isExists()) {
            $rekey = input('reid');
            //通过user_id查找
            $reuser = get_user_info($rekey);

            $user->reid = $reuser ? $reuser['user_id'] : 0;
        }

        $user->rekey = getReKey();
        $user->token = getToken();
        $user->save();

        $thirdUser->uid = $user->getKey();
        $thirdUser->save();

        return $user;
    }

    /**获取平台支付方式
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPayMethods(): Collection
    {
        $sceneMap = [
            PlatFormFactory::APP      => 3,
            PlatFormFactory::WECHAT   => 4,
            PlatFormFactory::BYTE     => 5,
            PlatFormFactory::OFFICIAL => 6,
        ];

        return Plugin::where('type', 'payment')
            ->where('status', 1)
            ->where('scene', $sceneMap[$this->platform])
            ->select();
    }

    public static function isApp(): bool
    {
        return request()->param('platform') === PlatFormFactory::APP;
    }

    public function getConfig($key = null)
    {
        return $key ? $this->config[$key] : $this->config;
    }
}